package 多线程.三个线程实现顺序打印;

import java.util.concurrent.Semaphore;

/**
 * 线程间同步,还可以使用信号量Semaphore,信号量顾名思义,多线程协作时完成信号传递
 * 使用acquire()获取许可,如果没有可用的许可,线程进入阻塞等待状态;使用release释放许可
 */
public class Test5 {
    private static Semaphore semaphoreB = new Semaphore(0);
    private static Semaphore semaphoreC = new Semaphore(0);
    public static void main(String[] args) {
        Test5 t = new Test5();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                t.printA();
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                try {
                    t.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread t3 = new Thread() {
            @Override
            public void run() {
                try {
                    t.printC();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t1.start();
        t2.start();
        t3.start();
    }

    public void printA() {
        System.out.println("A");
        semaphoreB.release();
    }

    public void printB() throws InterruptedException {
        semaphoreB.acquire();
        System.out.println("B");
        semaphoreC.release();
    }

    public void printC() throws InterruptedException {
        semaphoreC.acquire();
        System.out.println("C");
    }
}
